<template>
	<page ref="page">
		<u-sticky>
			<!-- 吸顶进度条,只能有一个根元素 -->
			<u-search placeholder="请输入关键字" shape="square" @clear="eventClear" @search="eventSearch" :show-action="false"
				v-model="keyword">
			</u-search>
		</u-sticky>
		 
		<u-button @click="eventGoDownloadsPage" type="primary">已下载</u-button>
		<u-button style="margin-top:20rpx;" @click="eventClearData" type="error">清空数据表</u-button>
		<u-button style="margin-top:20rpx;" @click="eventDeleteTable" type="error">删除数据表</u-button>
		<u-button style="margin-top:20rpx;" @click="eventInitTable" type="success">初始化数据表</u-button>
		<view v-for="(item,index) of resources" :key="'r_'+index" @click="eventGoDetailPage(item)">
			 
			<view v-if="item.status===2">
				<!-- 正在下载 -->
				<u-line-progress v-show="true" :striped="true" :percent="item.progress" :striped-active="true">
				</u-line-progress>
			</view>
			<view>
				<!-- 正在解析 -->
				<u-loading color="#2979ff" v-if="item.status===4">
				</u-loading>
				<u-icon v-show="item.status===1" name="checkmark-circle-fill" color="#55aa00" size="28">
					<!-- 下载成功 -->

				</u-icon>
				<u-icon v-show="item.status===3" name="close-circle-fill" color="#ff4e4e" size="28">
					<!-- 无效资源 -->
				</u-icon>
				<!-- item.status===0 是没下载过 -->
				{{item.title}}
			</view>
			<u-image :src="item.img" mode="widthFix">
				<u-loading color="#2979ff" slot="loading">
				</u-loading>
			</u-image>
		</view>
		<u-loadmore :status="status" :icon-type="iconType" :load-text="loadText" />
	</page>
</template>

<script>
	import page from '@/components/base-page/page.vue'
	import parser from './htmlparser/index.js'
	import resourceService from './downloader/db.js'
	import gbk from './utils/index.js'
	import linq from 'linq'
	export default {
		components: {
			page
		},
		data() {
			return {
				status: 'loadmore',
				iconType: 'flower',
				loadText: {
					loadmore: '轻轻上拉',
					loading: '努力加载中',
					nomore: '实在没有了'
				},
				resources: [],
				nextPageUrl: '',
				nextSearchPageUrl: '',
				rootUrl: 'https://www.zfl101.vip',
				baseUrl: 'https://www.zfl101.vip/luyilu',
				baseSearchUrl: 'https://s.soazs.vip:1599',
				keyword: '',
				tempSrc: ''
			}
		},
		computed: {
			searchUrl() {
				return `/serch.php?keyword=${gbk.encode(this.keyword)}&page=1`;
			}
		},
		onReachBottom() {
			if (this.keyword.length > 0) {
				if (this.nextSearchPageUrl.length === 0) return;
				this.loadSearchData(this.nextSearchPageUrl);
			} else {
				if (this.nextPageUrl.length === 0) return;
				this.loadData(this.nextPageUrl);
			}

		},
		onLoad() {
			this._onLoad();
		},
		mounted() {
			this.$bus.sub('onresourceprogress', this.updateResourceStatus)
		},
		methods: {
			updateResourceStatus({
				id,
				progress,
				status
			}) {
				const old = linq.from(this.resources).singleOrDefault(x => x.id === id)
				if (old) {
					old.status = status
					old.progress = progress
				}
			},
			onImgLoad(e) {
				console.log(e)
			},
			onImgError(e) {
				console.log(e)
			},
			eventGoDetailPage(item) {
				var navData = JSON.stringify(item); // 这里转换成 字符串
				uni.navigateTo({
					url: './detail?index=' + encodeURIComponent(navData)
				})
			},
			eventGoDownloadsPage() {
				console.log('点击跳转')
				uni.navigateTo({
					url: './downloads'
				})
			},
			/**
			 * 清空数据表
			 */
			eventClearData() {
				this.$message.confirm(() => {
					resourceService.clear().then(() => {
						this.$message.toast()
					})
				}, '确定要清空数据表吗？');
			},
			/**
			 * 删除数据表
			 */
			eventDeleteTable() {
				this.$message.confirm(() => {
					resourceService.drop().then(() => {
						this.$message.toast()
					})
				}, '确定要删除整张数据表吗？');
			},
			/**
			 * 初始化数据表
			 */
			eventInitTable() {
				this.$message.confirm(() => {
					resourceService.init().then(() => {
						this.$message.toast()
					})
				}, '确定要初始化数据表吗？');
			},
			async _onLoad() {
				await resourceService.open();
				this.loadData('/list_5_1.html');
			},
			eventClear() {
				this.resources = [];
				this.nextPageUrl = "";
				this.nextSearchPageUrl = "";
				this.$nextTick(() => {
					this._onLoad();
				})
			},
			eventSearch() {
				this.status = "loadmore";
				this.resources = [];
				this.loadSearchData(this.searchUrl);
			},
			async loadSearchData(url) {
				this.status = 'loading';
				const nextUrl = this.baseSearchUrl + url
				const resourceParser = new parser.resourceParser(nextUrl, () => {}, () => {});
				const firstPageResult = await resourceParser.parse()
				this.status = 'loadmore';

				if (firstPageResult.nextPageUrl === '') {
					this.status = 'nomore'
				}
				this.nextSearchPageUrl = firstPageResult.nextPageUrl.replace(this.keyword, gbk.encode(this.keyword));
				firstPageResult.resources.forEach(x => {
					x.id = x.url.substring(x.url.lastIndexOf('/') + 1).replace('.html', '')
					x.url = x.url.replace(this.rootUrl, '');
					x.status = 0
					x.progress = 0
					resourceService.get(x.id).then(res => {
						if (res) {
							x.status = 1
							x.progress = 100
						}
					})
				})
				this.resources = this.resources.concat(firstPageResult.resources)
			},
			async loadData(url) {
				this.status = 'loading';
				const nextUrl = this.baseUrl + url
				const resourceParser = new parser.resourceParser(nextUrl, () => {}, () => {});
				const firstPageResult = await resourceParser.parse()
				this.status = 'loadmore';
				if (firstPageResult.nextPageUrl === '') {
					this.status = 'nomore'
				}
				this.nextPageUrl = firstPageResult.nextPageUrl
				firstPageResult.resources.forEach(x => {
					x.id = x.url.substring(x.url.lastIndexOf('/') + 1).replace('.html', '')
					x.status = 0
					x.progress = 0
					resourceService.get(x.id).then(res => {
						if (res) {
							x.status = 1
							x.progress = 100
						}
					})
				})
				this.resources = this.resources.concat(firstPageResult.resources)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-demo {}
</style>
